package dicebot.apps;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Random;

import dicebot.abstracts.MessageHandler;
import dicebot.filene.Main;
import net.mamoe.mirai.contact.ContactList;
import net.mamoe.mirai.contact.Group;
import net.mamoe.mirai.contact.NormalMember;
import net.mamoe.mirai.event.events.GroupMessageEvent;

public class LittleGames {
	
	private static final String[] VOICES = new String[] {"喵。", "喵~", "喵呜~", "喵嗷！", "嗷呜！", "呜喵~"};
	private static final String DEFAULT_TEXT = "#nick蹭了蹭你的身子，看起来似乎很享受";
	private static final String DEFAULT_ENDFIX = "（好感度增加了#add，现在是#cur）";
    public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	private static NormalMember getRandomMember (Group group) {
		ContactList<NormalMember> members = group.getMembers();
		ArrayList<NormalMember> list = new ArrayList<>(members);
		int rand = new Random().nextInt(list.size());
		return list.get(rand);
	}

	private static NormalMember getRandomMemberExcluding (Group group, NormalMember excludes) {
		ContactList<NormalMember> members = group.getMembers();
		ArrayList<NormalMember> list = new ArrayList<>(members);
		list.remove(excludes);
		int rand = new Random().nextInt(list.size());
		return list.get(rand);
	}
	
	public static void initialize () throws SQLException {
		Statement statement = Sql.getStatement();
		statement.execute("create table if not exists Goodwills (Gr text not null, Fr text not null, Ta text not null, Goodwill int not null default 0, LastActionTime text not null, primary key (Gr, Fr, Ta));");
		statement.execute("create table if not exists GoodwillTexts (Gr text not null, QQ text not null, Message text not null, primary key (Gr, QQ));");
		statement.close();
		
		Main.HANDLERS.add(new MessageHandler() {
			@Override
			public boolean handle(GroupMessageEvent e) throws Exception {
				String msg = e.getMessage().contentToString();
				if (msg.equals("撅群友")) {
					Group group = e.getGroup();
					NormalMember member = getRandomMember(group);
					String voice = VOICES[new Random().nextInt(VOICES.length)];
					group.sendMessage(member.getNick() + "开始不受控制地乱叫：" + voice);
					return true;
				} else if (msg.equals("摸群友")) {
					Statement statement = Sql.getStatement();
					ResultSet r;
					Date date = new Date();
					
					// generate available targets
					Group group = e.getGroup();ContactList<NormalMember> members = group.getMembers();
					ArrayList<NormalMember> options = new ArrayList<>();
					ArrayList<NormalMember> optionsWithText = new ArrayList<>();
					for (NormalMember member : members) {
						// check if not the sender and not Filene herself
						if (member.getId() == e.getSender().getId() || member.getId() == e.getBot().getId()) {
							continue;
						}
						// check if action taken within a hour
						r = statement.executeQuery("select * from Goodwills where Gr = '" + group.getId() + "' and Ta = '" + member.getId() + "' and Fr = '" + e.getSender().getId() + "';");
						if (r.next()) {
							String lastAction = r.getString("LastActionTime");
							Date lastActionTime = DATE_FORMAT.parse(lastAction);
							if (date.getTime() - lastActionTime.getTime() < 86400000l) {
								continue;
							}
						}
						// add as an available option
						options.add(member);
						r = statement.executeQuery("select * from GoodwillTexts where Gr = '" + group.getId() + "' and QQ = '" + member.getId() + "';");
						if (r.next()) {
							optionsWithText.add(member);
						}
					}
					
					// roll a target
					if (options.isEmpty()) {
						group.sendMessage("你今天已经把群友都摸过一遍啦！快去休息一会吧~");
						statement.close();
						return true;
					}
					int rand = new Random().nextInt(options.size() + 5 * optionsWithText.size());
					NormalMember member;
					if (rand < options.size()) {
						member = options.get(rand);
					} else {
						member = optionsWithText.get((rand - options.size()) / 5);
					}
					
					// add goodwill
					int add = 1 + new Random().nextInt(10);
					int cur = 0;
					r = statement.executeQuery("select * from Goodwills where Gr = '" + group.getId() + "' and Ta = '" + member.getId() + "' and Fr = '" + e.getSender().getId() + "';");
					if (r.next()) {
						cur = r.getInt("Goodwill");
					}
					cur += add;
					statement.execute("insert or replace into Goodwills (Gr, Fr, Ta, Goodwill, LastActionTime) values ('"
							+ group.getId() + "', '" + e.getSender().getId() + "', '" + member.getId() + "', " + cur + ", '" + DATE_FORMAT.format(date) + "');");
				
					String message = DEFAULT_TEXT;
					r = statement.executeQuery("select * from GoodwillTexts where Gr = '" + group.getId() + "' and QQ = '" + member.getId() + "';");
					if (r.next()) {
						message = r.getString("Message");
					}
					if (!message.contains("#add") && !message.contains("#cur") && !message.contains("#lst")) {
						message = message + DEFAULT_ENDFIX;
					}
					String nick = member.getNameCard();
					if (nick == null || nick.isEmpty()) {
						nick = member.getNick();
					}
					message = message.replaceAll("#nick", nick);
					message = message.replaceAll("#add", add + "");
					message = message.replaceAll("#cur", cur + "");
					message = message.replaceAll("#lst", (cur - add) + "");

					group.sendMessage(message);
					statement.close();
					return true;
				} else if (msg.matches("我被摸的时候说.+")) {
					Statement statement = Sql.getStatement();
					
					String message = msg.substring("我被摸的时候说".length());
					statement.execute("insert or replace into GoodwillTexts (Gr, QQ, Message) values ('"
							+ e.getGroup().getId() + "', '" + e.getSender().getId() + "', '" + message + "');");

					e.getGroup().sendMessage("知道了~");
					statement.close();
					return true;
				}
				return false;
			}
		});
	}
	
}
